// 设置托盘事件
import { app, ipcMain, Menu, Tray } from 'electron'
import { resolveS } from '@/config/path_config'
import PARAME from '@/complete/param/parameterList'
const trayIcon = resolveS('logoImg/logo.png')
const trayMessageIcon = resolveS('otherImg/message.png')

let trayMain = null
let timerMessage = null

const createTray = function (win) {
  if (!win) { return }
  trayMain = new Tray(trayIcon)
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '刷新',
      click: function () {
        win.webContents.reload()
        win.show()
      }
    },
    {
      label: '设置',
      click: function () {
        win.webContents.send(PARAME.SET_SETTINT_PAGE_APP, true)
        win.show()
      }
    },
    {
      label: '退出',
      click: function () {
        win.destroy()
        app.quit()
      }
    }
  ])
  // 注册监听闪一闪
  ipcMain.on(PARAME.GETMESSAGETRAY_MAIN_APP, (e, flage) => {
    trayMessageFun(flage, trayMain)
  })

  trayMain.setToolTip('桌面宠物')
  trayMain.setContextMenu(contextMenu)
  trayMain.on('click', () => {
    // 是否显示窗口
    win.isVisible() ? win.hide() : win.show()
    // 是否显示任务栏
    // win.isVisible() ? win.setSkipTaskbar(false) : win.setSkipTaskbar(true)
  })
}

function trayMessageFun (type, newtray) {
  if (type) {
    let count = 0
    if (timerMessage) {
      clearInterval(timerMessage)
    }
    timerMessage = setInterval(function () {
      count++
      if (count % 2 === 0) {
        newtray.setImage(trayIcon)
      }
      else {
        newtray.setImage(trayMessageIcon)
      }
    }, 500)
  }
  else {
    clearInterval(timerMessage)
    newtray.setImage(trayIcon)
  }
}

export { createTray }
